#!/bin/ksh

m=8 ; # m=8: surface station, 9: automatic weather station
for x in antarc1.txt antarc3.txt
do if [[ m -eq 8 ]] ; then echo 'collecting surface station data' ; fi
   if [[ m -eq 9 ]] ; then echo '... and autom. weather stn data' ; fi
   while read a
   do if [[ $a = '' ]] ; then continue ; fi
      if [[ $a = 'Get '* ]] ; then continue ; fi
      if [[ $a != [12A-Z]* ]] ; then continue ; fi
      if [[ $a = *' temperature'* ]]                            ; # header line
      then name=${a%% *}                                        ; # get name to
        b=$( grep " ${name} " input_files/${x%.txt}.list )      ; # find ID
        id=${b%% *}                                             ; # from ...list
      elif [[ $a != *'.'* ]] ; then continue                    ; # skip no-data-lines
      elif [[ $a = [12]* ]] then  echo "${id}${m}$a " >> v2_antarct.dat
      fi
   done < input_files/$x
   (( m = m+1 ))
done
         echo "... and australian data"
m=7  ; # marker for australian stations
while read a
do if [[ $a = '' ]] ; then continue ; fi
   if [[ $a = *':'* ]] ; then continue ; fi
   name=${a%%'  '*} ; b=${a#${name}}
   if [[ $b = *'E' || $b = *'E '* ]]                                   ; # header line
   then b=$( grep " ${name} " input_files/antarc2.list ) ; id=${b%% *} ; # get ID
   elif [[ $a != [12]* ]] ; then continue                              ; # skip non-data-lines
   elif [[ $a != *'.'* ]] ; then continue                              ; # skip no-data-lines
   else echo "${id}${m}$a " >> v2_antarct.dat
   fi
done < input_files/antarc2.txt
echo "replacing '-' by -999.9, blanks are left alone at this stage"
sed 's/       - /  -999.9 /g' < v2_antarct.dat > v2_antarct.datt
sed 's/       - /  -999.9 /g' < v2_antarct.datt > v2_antarct.dat
sort v2_antarct.dat > v2_antarct.datt
mv -f v2_antarct.datt v2_antarct.dat
